from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from forms import BasicSettingsForm, InterfacesForm
from models import Setting,Interface
from oms.api import system
import api

def index(request):
    return render_to_response('system/index.html')

def basic(request):
    if request.method == 'POST':
        form = BasicSettingsForm(request.POST)
        if form.is_valid():
            for key in form.cleaned_data.keys():
                setting,created = Setting.objects.get_or_create(key=key)
                setting.value = form.cleaned_data[key]
                setting.save()
            system("system.api.set_hostname")
            system("system.api.set_dns")
            system("system.api.set_default_gateway")
            return HttpResponseRedirect(reverse("system-basic-settings"))
    else:
        form = BasicSettingsForm()
        form_data = {}
        for field in form.fields.keys():
            try:
                value = Setting.objects.get(key=field).value
            except:
                if field == "primary_dns":
                    value = api.get_dns()[0]
                elif field == "secondary_dns":
                    dnss = api.get_dns()
                    if len(dnss) > 1:
                        value = api.get_dns()[1]
                    else:
                        value = ""
                elif field == "gateway":
                    value = api.get_default_gateway()
                elif field == "hostname":
                    value = api.get_hostname()
                elif field == "domain":
                    value = api.get_domain()
                else:
                    value = form[field].field.initial or ""
            form_data[field] = value
        form = BasicSettingsForm(form_data)
    return render_to_response('system/basic.html', {
        'basic_settings_form': form,
    })

def interfaces(request):
    forms = []
    added_interface=None
    if request.method == 'POST':
        form = InterfacesForm(request.POST,instance=Interface.objects.get_or_create(name=str(request.POST["name"]))[0])
        if form.is_valid():
            form.save()
            system("system.api.set_interface %s" % request.POST["name"])
            return HttpResponseRedirect(reverse("system-interfaces"))
        else:
            added_interface = str(request.POST["name"])
            forms.append((added_interface,form,))
    for interface in api.get_interfaces():
        if not added_interface or not added_interface == interface:
            if Interface.objects.filter(name=interface).count()>0:
                forms.append(
                        (interface,InterfacesForm(instance=Interface.objects.get(name=interface))),
                            )
            else:
                forms.append((interface,InterfacesForm({
                    'name':interface,
                    'dhcp':api.get_interface_dhcp(interface),
                    'ip':api.get_interface_ip(interface),
                    'mask':api.get_interface_mask(interface),
                    'enabled':api.get_interface_enabled(interface),
                        }),))
    forms.sort()
    return render_to_response('system/interfaces.html',{'interfaces_forms' : forms,})


def services(request):
    if request.method == 'POST':
        if request.POST.has_key("stop"):
            system("system.api.service_stop %s" % request.POST["service"])
        elif request.POST.has_key("start"):
            system("system.api.service_start %s " % request.POST["service"])
        elif request.POST.has_key("enable"):
            system("system.api.service_enable %s " % request.POST["service"])
        elif request.POST.has_key("disable"):
            system("system.api.service_disable %s " % request.POST["service"])
    services = []
    for service in api.SERVICES:
        services.append(
                (service,
                 system("system.api.service_running %s" % service)[1].strip() == "YES",
                 system("system.api.service_enabled %s" % service)[1].strip() == "YES",
                 )
                )
    return render_to_response('system/services.html',{"services":services})

